package tictacstego;

/**
 * Project 4 -- TTTManager
 * 
 * This class implements a Manager for Tic-Tac-Toe
 * that runs games between 2 agents and records the
 * games played by the agents.
 * 
 * TODO: Replace the usernames below with your Purdue usernames. 
 * During grading, Web-CAT will automatically detect team members 
 * from these tags, so you will not need to click "Choose Partners" 
 * when submitting.
 * 
 * @author chengf
 * @author zheng204
 */

import java.util.LinkedList;

import interfaces.GameManager;

public class TTTManager implements GameManager {
	// Player 1's agent
	private TTTAgent p1;
	
	// Player 2's agent
	private TTTAgent p2;
	
	// Gameplay history - list of gameplay records
	private LinkedList<String> history;
	
	/**
	 * Construct a new TTTManager to run games between two given agents
	 * @param p1 - the first player's agent
	 * @param p2 - the second players agent
	 */
	public TTTManager(TTTAgent p1, TTTAgent p2) {
		// initialize the instance variables with the given agents
		this.p1 = p1;
		this.p2 = p2;
		
		// initialize the list of gameplay records
		history = new LinkedList<String>();
	}

	@Override
	public int runGame() {
		// construct a new board
		TTTBoard b = new TTTBoard();
		
		// tell both agents to prepare for a new game
		p1.newGame();
		p2.newGame();
		
		// declare some useful variables
		String move;	// to store an agent's selected move
		TTTAgent cA;	// to store the current players agent 
		
		// make an empty gameplay record
		String gameplay = "";
		
		// while the board is neither in a winning state, nor in a draw state,
		while (!(b.hasWin() || b.hasDraw())) {
			// use the current player's agent
			cA = b.getCurrentPlayer() == 1 ? (TTTAgent)p1 : (TTTAgent)p2;
			
			// get the next move from the current player's agent
			move = cA.getMove(b);
			
			// play the move on the board
			b.playMove(move);
			
			// add the move to the gameplay record
			gameplay += move + ",";
		}
		
		// add the gameplay record to the list of gameplay records
		history.add(gameplay);
		
		// return the id of the winner, or 0 for a draw
		return b.hasWin() ? 3 - b.getCurrentPlayer() : 0;
	}

	@Override
	public int[] runAllTheGames() {
		// declare and initialize the win-lose-draw (WLD) record
		int[] record = new int[]{0, 0, 0};
		
		// while either player still wants to play,
		while (p1.askNewGame() || p2.askNewGame()) {
			// run a game and use the result to update the WLD record
			record[(runGame() + 2) % 3]++;
		}

		// return the WLD record
		return record;
	}
	
	@Override
	public String[] getHistory() {
		// return the list of games played as an array
		return history.toArray(new String[0]);
	}
}
